package memorphic.samplr.controllers
{
	import com.adobe.webapis.flickr.FlickrService;
	import com.adobe.webapis.flickr.PagedPhotoList;
	import com.adobe.webapis.flickr.Photo;
	import com.adobe.webapis.flickr.PhotoSize;
	import com.adobe.webapis.flickr.events.FlickrResultEvent;
	
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.IOErrorEvent;
	import flash.filesystem.File;
	import flash.filesystem.FileMode;
	import flash.filesystem.FileStream;
	import flash.net.URLLoader;
	import flash.net.URLLoaderDataFormat;
	import flash.net.URLRequest;
	
	import memorphic.samplr.models.Gallery;
	import memorphic.samplr.models.SamplrPhoto;
	import memorphic.samplr.services.ServiceLocator;
	
	import mx.collections.ArrayCollection;
	
	public class FlickrDelegate extends EventDispatcher
	{
		public static const FLICKR_URL_BASE:String = "http://farm1.static.flickr.com/";
		
		private static const THUMBNAIL_SIZE_IMAGE_URL_SUFFIX:String = "t";
		private static const ORIGINAL_SIZE_IMAGE_URL_SUFFIX:String = "o";
		private static const LARGE_SIZE_IMAGE_URL_SUFFIX:String = "b";
		
		public function FlickrDelegate()
		{
		}
		
		public function getInterestingPics():void
		{
			var flickrService:FlickrService = ServiceLocator.getFlickrService();
			flickrService.addEventListener(FlickrResultEvent.INTERESTINGNESS_GET_LIST,onGetInterestingPics);
			flickrService.addEventListener(IOErrorEvent.IO_ERROR, onIOError);
			flickrService.interestingness.getList();
		}
		
		private function onGetInterestingPics(evt:FlickrResultEvent):void
		{
			FlickrService(evt.target).removeEventListener(FlickrResultEvent.INTERESTINGNESS_GET_LIST,onGetInterestingPics);
			FlickrService(evt.target).removeEventListener(IOErrorEvent.IO_ERROR, onIOError);
			if (evt.success)
			{
				var event:FlickrResultEvent = new FlickrResultEvent(FlickrResultEvent.INTERESTINGNESS_GET_LIST);
				event.success = evt.success;
				event.data.photos = pagedPhotoListToArrayCollection(PagedPhotoList(evt.data.photos));
				dispatchEvent(event);
			}
		}
		
		private function pagedPhotoListToArrayCollection(ppList:PagedPhotoList):ArrayCollection
		{
			var photos:ArrayCollection = new ArrayCollection();
			
			for each (var photo:Photo in ppList.photos)
			{
				var samplrPhoto:SamplrPhoto = new SamplrPhoto();
				
				samplrPhoto.title = photo.title;
				samplrPhoto.id = photo.id;
				samplrPhoto.secret = photo.secret;
				samplrPhoto.flickrURLThumbnail = FLICKR_URL_BASE + photo.server +
					"/" + samplrPhoto.uniqueID + "_" + THUMBNAIL_SIZE_IMAGE_URL_SUFFIX + ".jpg";
				
				samplrPhoto.flickrURLMedium = FLICKR_URL_BASE + photo.server +
					"/" + samplrPhoto.uniqueID + ".jpg";
				
				photos.addItem(samplrPhoto);
			}
			return photos;
		}
		
		public function getPhotoSizes(photo:SamplrPhoto, gallery:Gallery):void
		{
			var service:FlickrService = ServiceLocator.getFlickrService();
			service.addEventListener(IOErrorEvent.IO_ERROR, onIOError);
			service.addEventListener(FlickrResultEvent.PHOTOS_GET_SIZES,
				function onGetSizes(evt:FlickrResultEvent):void
				{
					FlickrService(evt.target).removeEventListener(FlickrResultEvent.PHOTOS_GET_SIZES, onGetSizes);
					if (evt.success)
					{
						var len:int = evt.data.photoSizes.length;
						for (var i:int = 0 ; i < len ; i++)
						{
							writePhotoSizeToFile(photo, evt.data.photoSizes[i], len, gallery);
						}
					}
				}
			);
			service.photos.getSizes(photo.id);
		}
		
		private function writePhotoSizeToFile(photo:SamplrPhoto, photoSize:PhotoSize, numSizes:int, gallery:Gallery):void
		{
			var loader:URLLoader = new URLLoader();
			loader.addEventListener(Event.COMPLETE,
				function onPhotoSizeLoaded(evt:Event):void
				{
					loader.removeEventListener(Event.COMPLETE, onPhotoSizeLoaded);
					var p:SamplrPhoto = photo;
					var galleryDir:File = new File(gallery.url);
					var imageFile:File = galleryDir.resolvePath(photo.uniqueID + "_" + photoSize.label.toLowerCase() + ".jpg");
					var fs:FileStream = new FileStream();
					fs.openAsync(imageFile, FileMode.WRITE);
					fs.writeBytes(loader.data);
					fs.close();
					
					photoSize.source = imageFile.url;
					p["source" + photoSize.label] = imageFile.url;
					p.photoSizes.push(photoSize);
					if (p.photoSizes.length == numSizes)
					{
						writePhotoObject(p, gallery);
					}
				}
			);
			loader.dataFormat = URLLoaderDataFormat.BINARY;
			loader.load(new URLRequest(photoSize.source));
		}
		
		private function writePhotoObject(photo:SamplrPhoto, gallery:Gallery):void
		{
			var samplrPhotoFile:File = new File(gallery.url).resolvePath(photo.uniqueID + ".smp");
			var fs:FileStream = new FileStream();
			fs.openAsync(samplrPhotoFile, FileMode.WRITE);
			fs.writeObject(photo);
			fs.close();
			dispatchEvent(new FlickrResultEvent(FlickrResultEvent.PHOTOS_GET_SIZES));
		}
		
		private function onIOError(evt:IOErrorEvent):void
		{
			trace(evt.text);
		}
	}
}